﻿namespace BEGDC.CC.Web.EZVisit.Common
{
    #region Using Directives

    using System;
    using System.IO;
    using System.Security.Principal;
    using System.Text;
    using System.Web;
    using ASBCC.Database.Service;
    using ASBCC.Utility;
    using Utility.Extensions;
    using Workflow;

    #endregion

    public partial class EZVAttachmentExport : BasePage, IEZVisitPageAccess
    {
        #region IEZVisitPageAccess Members

        public EZVisitAccessControl AccessControl { get; set; }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.Request.QueryString["FileID"].IsNotNullOrWhiteSpace())
            {
                int id;

                if (int.TryParse(this.Request.QueryString["FileID"], out id))
                {
                    var file = UploadFileManager.SelectByKeys(id);

                    if (file != null && file.IsEnabled != null && file.IsEnabled.Value && this.CheckPermission(file.AppID.Value))
                    {
                        this.ExportFile(file.FilePath, file.FileName);
                    }
                }
            }
        }

        private bool CheckPermission(int appId)
        {
            this.AccessControl = new EZVisitAccessControl(this.UserInfo, appId);

            if (!this.AccessControl.HasViewPermission)
            {
                this.Response.Write("<script type=\"text/javascript\">alert('You were not granted the permission to view this page.\\n\\n您没有查看此页面的权限。');window.opener = null;window.close();</script>");
                return false;
            }

            return true;
        }

        private void ExportFile(string sourceFile, string fileName)
        {
            using (WindowsImpersonationContext context = UploadUtility.NetworkImpersonateUser())
            {
                if (!File.Exists(sourceFile))
                {
                    this.Response.Write("<script type=\"text/javascript\">alert('The attachment was moved or deleted. Please contact the system admin for help.\\n\\n此附件已被移动或删除。');window.opener = null;window.close();</script>");
                    return;
                }

                string fileServer = ConfigUtility.UploadServerIP;
                string ezvisitFolder = ConfigUtility.EZVisitDocument;

                using (var fileStream = new FileStream(sourceFile, FileMode.Open))
                {
                    try
                    {
                        long fileSize = fileStream.Length;
                        this.Response.Buffer = true;

                        this.Response.ContentType = "application/octet-stream";
                        //中文文件名需要UTF8编码
                        this.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + HttpUtility.UrlEncode(fileName, Encoding.UTF8) + "\"");
                        this.Response.AddHeader("Content-Length", fileSize.ToString());

                        if (fileSize > 0)
                        {
                            var fileBuffer = new byte[fileSize];
                            fileStream.Read(fileBuffer, 0, (int) fileSize);
                            this.Response.BinaryWrite(fileBuffer);
                        }

                        this.Response.Flush();
                        this.Response.End();
                    }
                    catch (Exception e)
                    {
                        this.Response.Write("<script type=\"text/javascript\">alert('Unknown error occured, please contact system admin for help.');window.opener = null;window.close();</script>");
                    }
                }

                context.Undo();
            }
        }
    }
}